package com.george.service.impl;

import com.george.properties.FileExtProp;
import com.george.properties.FileProp;
import com.george.properties.OaProperties;
import com.george.service.FileUploadService;
import com.google.common.io.Files;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author GeorgeChan 2019/4/25 11:37
 * @version 1.0
 * @since jdk1.8
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    // 打印日志
    private static Logger LOGGER = LoggerFactory.getLogger(FileUploadService.class);
    @Autowired
    private OaProperties oaProperties;
    @Override
    public boolean uoloadSingleImage(MultipartFile imagefile){
        // 获取文件后缀
        String fileExtension = Files.getFileExtension(imagefile.getOriginalFilename());

        // 获取配置文件的属性
        FileProp file = oaProperties.getFile();
        String uploadPath = file.getUploadPath();
        FileExtProp exts = file.getExts();
        List<String> image = exts.getImage();
        // 判断图片格式是否合法
        boolean contains = image.contains(fileExtension);
        if (!contains) {
            return false;
        }
        // 生成文件名 时间+随机数
        String timeFormat = DateUtil.format(new Date(), "YYYYMMddHHmmss");
        String ramdom = RandomUtil.randomNumbers(6);
        String imageName = timeFormat + ramdom + "." + fileExtension;
        // 上传路径
        String path = uploadPath + imageName;
        try {
            // 把图片写入服务器并返回了存储路径
            File file1 = FileUtil.writeBytes(imagefile.getBytes(), path);
            LOGGER.info("文件上传路径为:=====》  {}", file1.toString());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
